package com.ev.util;

import com.ev.anno.ExcelFieldName;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description:
 * @Author: GuoShouFu
 * @Date: 2022/6/28
 **/
public class XlsExcelUtil {

    /**
     * 一行数据转化为数据实体（第一行为属性字段）
     *
     * @param read  xls一个sheet所有的内容
     * @param clazz 要转化为的实体对象
     * @param <T>
     * @return
     * @throws Exception
     */
    public static <T> List<T> listStringConvert2Entity(List<List<String>> read, Class<T> clazz) throws Exception {
        List<String> excelFieldList = read.get(0);
        Field[] fields = clazz.getDeclaredFields();

        List<T> rusult = new ArrayList<>();
        for (int i = 1; i < read.size(); i++) {
            List<String> rowList = read.get(i);
            T instance = clazz.newInstance();
            for (Field field : fields) {
                field.setAccessible(true);
                if (field.isAnnotationPresent(ExcelFieldName.class)) {
                    String value = field.getAnnotation(ExcelFieldName.class).value();
                    Integer columnIndex = getColumnIndex(excelFieldList, value);
                    field.set(instance, rowList.get(columnIndex));
                }
            }
            rusult.add(instance);
        }

        return rusult;
    }

    /**
     * 获得value对应第一行属性的索引值
     *
     * @param excelFieldList 第一行属性集合
     * @param value          属性名
     * @return
     */
    private static Integer getColumnIndex(List<String> excelFieldList, String value) {
        for (int i = 0; i < excelFieldList.size(); i++) {
            if (value.equals(excelFieldList.get(i))) {
                return i;
            }
        }
        throw new RuntimeException("数据异常");
    }

}
